import 'package:connectivity/connectivity.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:ymt/api/apis.dart';
import 'package:ymt/db/offline_database_provider.dart';
import 'package:ymt/model/product.dart';
import 'package:ymt/utils/image.dart';
import 'package:ymt/utils/request.dart';


class FilterPage extends StatefulWidget{

  final _companyId;
  final _pageContext;

  FilterPage(this._companyId, this._pageContext);

  @override
  State<StatefulWidget> createState() {
    return _PageState(_companyId, _pageContext);
  }
}

class _PageState extends State<FilterPage>{

  Dio dio;
  List _filters;
  List _originFilters = List();
  List _filterMaps;

  List<Widget> _selectFilterItems;
  List<String> _selectFilterText;

  List<Hero> _filtersBars;
  List<Hero> _removedFiltersBars;

  int _pageIndex = 1;
  var _products = <Product>[];

  final _companyId;
  var _currentName;
  var _currentFilter;

  Map<String,int> _sortMap = Map();

  bool _loadOffline = false;

  Database _db;

  final _pageContext;

  _PageState(this._companyId, this._pageContext);

  @override
  void initState() {
    initData();
    initDio();
    executeTask();
    super.initState();
  }

  void initData(){
    _currentName = "热门风格";
    _selectFilterItems = List();
    _filtersBars =List();
    _removedFiltersBars = List();
    _selectFilterText = List();
  }

  executeTask() async {
    var connectivityResult = await Connectivity().checkConnectivity();
    print(connectivityResult);
    if (connectivityResult == ConnectivityResult.none) {
      _loadOffline = true;
    }else{
      _loadOffline = false;
    }
    getFilterOptions();
    getProducts({
      "company_id": _companyId,
      "name": _currentName,
      "page": _pageIndex
    });
  }

  void initDio(){
    dio = Request.dio();
  }

  @override
  Widget build(BuildContext context) {
    _filtersBars = List();
    if(_filters != null){
      for (int i = 0; i < _filters.length; i++) {
        var item = _filters[i];
        var tag = i;//item.name
        _filtersBars.add(_buildFilterBarContainer(_buildFilterBar(item, tag),
            EdgeInsets.only(left: 10, right: 10), tag));
      }
    }
    Container filterBarsContainer = Container(child: Column(children: _filtersBars,),margin: EdgeInsets.only(top: 10),);
    Widget content = Expanded(child: _buildGrid(),);
    List<Widget> verticalsChildren = [_buildSelectFilterBar(),  filterBarsContainer, content];
    Widget verticalContainer = _buildVerticalContainer(verticalsChildren);
    return verticalContainer;
  }

  Widget _buildSelectFilterBar() {
    return Container(margin: EdgeInsets.only(top: 33, left: 20),
      child: Row(children: <Widget>[Text("筛选",style: TextStyle(fontSize: 20,color: Color.fromARGB(255, 242, 203, 5)),), Row(children: _selectFilterItems,)],),);
  }

  Widget _buildFilterBarContainer(child, margin, tag) {
    return Hero(child: Container(child: child, height: 30, margin: margin,),tag: tag,);
  }

  Widget _buildFilterBar(option,tag) {
    String itemString = option["values"];
    List<String> items = itemString.split(",");
    items.insert(0, "不限"+option["name"]);
    return ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: items.length,
        itemBuilder: (context, position) {
          if(items.isNotEmpty) {
            return _buildTextContainer(
                _buildFilterItem(option["name"], items[position], tag));
          }else{
            return Container();
          }
        });
  }

  Widget _buildTextContainer(child) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 10), child: child,);
  }

  Widget _buildFilterItem(String name, String filterText, tag){
    // 记住当前分类
    var textColor = Colors.white;
    /*if(_currentCategory != null){
      if(_currentCategory.id == category.id){
        textColor = Color.fromARGB(255, 242, 203, 5);
      }
    }*/
    return click(Text(filterText,style: TextStyle(color: textColor),), () => {
      //选中栏添加选中项，筛选栏移除筛选项
      clickFilterItem(filterText, tag, name),
    });
  }


  void clickFilterItem(filterText,tag, filterName){
    _pageIndex = 1;
    setState(() {
      //1.顶部选中栏添加筛选项
      _selectFilterItems.add(_buildTextWithClose(filterText,tag, filterName));
      //2.筛选栏移除当前栏
      // 找出Hero添加到移除栏，然后恢复时还要保存顺序
      //Hero filterBar = findFilterBar(tag);
      int index = findFilterBarIndex(tag);
      Hero hero = _filtersBars.removeAt(index);
      _removedFiltersBars.add(hero);

      _filters.removeAt(index);

      _products.clear();
    });

    _selectFilterText.add(filterText);
    List<String> keys = List();
    _selectFilterText.forEach((item){
      if(!item.startsWith("不限")){
        keys.add(item);
      }
    });

    print(keys.length);
    var name = keys.removeAt(0);
    _currentName = name;
    var filter = keys.join(",");
    _currentFilter = filter;
    print(name);
    if(tag == 0){
      String values = findValues(name);
      replaceCategory(filterName, values);
    }
    //请求
    getProducts({
      "company_id": _companyId,
      "name": name,
      "filter": filter,
      "page": _pageIndex
    });
  }

  Widget _buildTextWithClose(text, tag, name) {
    return Hero(child: Container(child: OutlineButton(
      child: buildButtonColumn(text, Icons.close), onPressed: () =>{
      //1.移除选中，恢复筛选栏
      setState(() {
        int index = findIndexOfSelectFilters(text);
        _selectFilterItems.removeAt(index);
        _selectFilterText.remove(text);

        var removed = findElement(name);
        print(removed);
        _filters.add(removed);
        resortFilters();
      })
    },), margin: EdgeInsets.only(left: 10),), tag: text,);
  }

  findElement(String name){
    for(var item in _originFilters){
      if(name.compareTo(item["name"]) == 0){
        return item;
      }
    }
  }

  resortFilters() {
    _filters.sort((a, b) {
      var aName = a["name"];
      var bName = b["name"];
      return _sortMap[aName] - _sortMap[bName];
    });
  }

  int findIndexOfSelectFilters(String text){
    for(int i= 0; i< _selectFilterItems.length; i++){
      Hero child = _selectFilterItems[i];
      if(text.compareTo(child.tag)==0){
        return i;
      }
    }
    return -1;
  }

  Row buildButtonColumn(String label, IconData icon) {
    Color color = Colors.white;
    return new Row(
      mainAxisSize: MainAxisSize.min,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [ new Text(
            label,
            style: new TextStyle(
              color: color,
            ),
          ),
        new Icon(icon, color: color),
      ],
    );
  }

  int findFilterBarIndex(tag){
    if (_filtersBars != null) {
      Hero result;
      int length = _filtersBars.length;
      for (int i = 0; i < length; i++) {
        Hero child = _filtersBars[i];
        if(child.tag == tag){
          return i;
        }
      }
    }
  }

  Widget _buildVerticalContainer(widgets){
    return Column(children: widgets,);
  }

  void getFilterOptions() async {
    if(_loadOffline){
      OfflineDatabaseProvider().open((Database db) async {
        _db = db;
        List<Map> data = await db.query(OfflineDatabaseProvider.TABLE_FILTER_OPTIONS,);
        setState(() {
          _filters = data.map((e){
            Map map = Map();
            map["name"] = e["name"];
            map["values"] = e["value"];
            return map;
          }).toList();
          for (int i = 0; i < _filters.length; i++) {
            var item = _filters[i];
            _sortMap[item["name"]] = i;
            _originFilters.add(item);
          }
          print(_filters);
        });
        List<Map> maps = await db.query(OfflineDatabaseProvider.TABLE_FILTER_OPTIONS_MAPS,);
        _filterMaps = maps.map((e){
          Map map = Map();
          map["name"] = e["name"];
          map["values"] = e["value"];
          return map;
        }).toList();
      });
    }else {
      try {
        var response = await dio.get(ApiPaths.FILTER_OPTIONS,);
        //刷新UI
        setState(() {
          _filters = response.data["data"];
          for (int i = 0; i < _filters.length; i++) {
            var item = _filters[i];
            _sortMap[item["name"]] = i;
            _originFilters.add(item);
          }
          _filterMaps = response.data["maps"];
        });
      } catch (e) {
        print(e);
      }
    }
  }

  String findValues(String name){
    for(var e in _filterMaps){
      if(name.compareTo(e["name"]) == 0){
        String values = e["values"];
        return values;
      }
    }
    return null;
  }

  void replaceCategory(String name,String values){
    for(var e in _filters){
      if("类别".compareTo(e["name"]) == 0){
        e["values"] = values;
        break;
      }
    }
  }

  Widget _buildGrid() {
    return new GridView.builder(
      padding: EdgeInsets.only(left: 22, right: 22,),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          mainAxisSpacing: 12,
          crossAxisSpacing: 12,
          crossAxisCount: 4,
          childAspectRatio: 16 / 9),
      itemBuilder: (context, position) {
        if (_products != null && _products.isNotEmpty) {
          if (position == _products.length) {
            //分页加载
            _pageIndex++;
            getProducts({
              "company_id": _companyId,
              "name": _currentName,
              "filter": _currentFilter,
              "page": _pageIndex
            });
          }
          if (position < _products.length) {
            return _buildImage(_products[position].main_picture, position);
          }
        }
        return Container();
      }, itemCount: _products.length + 1,
      physics: BouncingScrollPhysics(),
    );
  }

  void getProducts(params) async {
    if(_loadOffline){
      //找出所有标签的id

      OfflineDatabaseProvider().open((Database db) async {
        String tagIdAndSql;
        var name = params["name"];
        print(params);
        var nameIds = await db.query(OfflineDatabaseProvider.TABLE_SEARCH_TAGS, where: "name = ?", whereArgs: [name]);
        print(nameIds);
        if(nameIds.length > 0 ){
          var first = nameIds[0];
          print(first);
          if(first.containsKey("id")){
            tagIdAndSql = first["id"].toString();
          }
        }
        print(tagIdAndSql);

        String filters = params["filter"];
        if(filters != null){
          List<String> filterList = filters.split(",");
          filterList.forEach((tag) async {
            var filterIds = await _db.query(OfflineDatabaseProvider.TABLE_SEARCH_TAGS, where: "name = ?", whereArgs: [tag]);
            if(filterIds.length > 0) {
              print(tag);
              String childSql = " SELECT product_id FROM " +
                  OfflineDatabaseProvider.TABLE_PRODUCT_SEARCH_TAGS +
                  " WHERE company_id = $_companyId and search_tag_id = ${filterIds[0]["id"]}";
              String sql = " AND tags.product_id IN (" + childSql + ")";
              tagIdAndSql = tagIdAndSql + sql;
            }else{
              print("未查询到离线数据");
            }
          });
          print("end");
        }
        print(tagIdAndSql);
        if(tagIdAndSql == null){
          return;
        }
        var page = params["page"];
        int offset = 12 * (page - 1);
        String sql = "SELECT p.id,p.main_picture,p.name,p.thumb_picture,p.company_id,p.retail_rate,p.product_category_id FROM "+ OfflineDatabaseProvider.TABLE_PRODUCT_SEARCH_TAGS + " tags LEFT JOIN products p ON tags.product_id = p.id  "  +
            "WHERE tags.company_id = $_companyId AND tags.search_tag_id = "+ tagIdAndSql+
            " ORDER BY tags.position LIMIT 12 OFFSET $offset";
        List<Map> maps  = await _db.rawQuery(sql);
        List<Product> list = List();
        list = maps.map((e){
          return  Product.fromMap(e);
        }).toList();
        updateProducts(params, list);
      });
    }else {
      try {
        //isLoadComplete = false;
        var response = await dio.get(ApiPaths.FILTER, queryParameters: params);
        List<Product> list = List<Product>.from(response.data.map((e) => Product.fromJson(e)).toList());
        updateProducts(params, list);
      } catch (e) {
        print(e);
      }
    }
  }

  void updateProducts(params, List<Product> list) {
    var page = params["page"];
    if (list.isNotEmpty) {
      // 返回了数据则追加数据，刷新UI
      setState(() {
        _products.addAll(list);
      });
    } else {
      // 如果第一页数据为空，并且当前有数据则清空产品列表
      if (page <= 1) {
        if (_products.isNotEmpty) {
          print("请求第$page页，返回${_products.length}条数据");
          setState(() {
            _products.clear();
          });
        }
      }
    }
  }

  Widget _buildImage(img, position){
    return CacheImage.imageClickToDetails(_pageContext, img, _products, position);
  }

  Widget click(child, onTap) {
    return GestureDetector(child: child, onTap: onTap,);
  }
}